package com.xzl.org.learning_situation_analysis.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.xzl.org.learning_situation_analysis.util.*;
import lombok.extern.slf4j.Slf4j;
import com.xzl.org.learning_situation_analysis.entity.User;
import com.xzl.org.learning_situation_analysis.response.RestResponse;
import com.xzl.org.learning_situation_analysis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 夏智力
 * @FileName LoginController
 * @date 2022/4/12 17:31
 * @Software: IntelliJ IDEA
 */
@Controller
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${server.servlet.context-path}")
    private String contextPath;




    @PostMapping("login")
    public RestResponse login(@RequestBody User loginUser) throws Exception {
        log.info(loginUser.toString());
        Result<JSONObject> result = new Result<JSONObject>();
        String username = loginUser.getUserName();


        User user = userService.selectByUserName(username);
        String userpassword = GenericUtil.md5(loginUser.getPassword() + user.getSalt());
        String syspassword = user.getPassword();

        if (!syspassword.equals(userpassword)) {
            return MessageUtils.fail("用户名或密码错误");
        }

        //用户登录信息
        userInfo(user, result);

        return MessageUtils.success(result.getResult());
    }

    private Result<JSONObject> userInfo(User sysUser, Result<JSONObject> result) {
        String syspassword = sysUser.getPassword();
        String username = sysUser.getUserName();
        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        redisTemplate.opsForValue().set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        // 设置超时时间
        redisTemplate.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000, TimeUnit.SECONDS);

        // 获取用户部门信息
        JSONObject obj = new JSONObject();
        obj.put("token", token);
        obj.put("userInfo", sysUser);
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/logout")
    public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        //用户退出逻辑
        String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
        if (GenericUtil.isEmpty(token)) {
            return Result.error("退出登录失败！");
        }
        String username = JwtUtil.getUsername(token);
        User sysUser = userService.selectByUserName(username);
        if (sysUser != null) {
            //清空用户Token缓存
            redisTemplate.delete(CommonConstant.PREFIX_USER_TOKEN + token);
            //清空用户权限缓存：权限Perms和角色集合
            redisTemplate.delete(CommonConstant.LOGIN_USER_CACHERULES_ROLE + username);
            redisTemplate.delete(CommonConstant.LOGIN_USER_CACHERULES_PERMISSION + username);
            return Result.ok("退出登录成功！");
        } else {
            return Result.error("无效的token");
        }
    }

    //生成验证码
    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response) {
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        //验证码归属
        String kaptchaOwner = GenericUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        //将验证码存入Redis
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(redisKey, text, 60 , TimeUnit.SECONDS);

        // 将图片输出浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.getMessage();
        }
    }
}
